#include"getTicket.hpp"
#include<vector>
using namespace ThreadMoudle;

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
int ticket = 1000;
// void getTicket(const std::string &name)
// {
//     pthread_mutex_lock(&gmutex);
//     while (ticket > 0)
//     {
//         usleep(1000);
//         ticket--;
//         std::cout << name << "buy ticket:" << ticket << std::endl;
//         pthread_mutex_unlock(&gmutex);
//     }
// }

//锁的使用（互斥）
void getTicket(ThreadData* td)
{
    while (true)
    {
        pthread_mutex_lock(td->_lock);
        if(ticket >0)
        {
            usleep(1000);
            ticket--;
            std::cout << td->_name << "buy ticket:" << ticket << std::endl;
            pthread_mutex_unlock(td->_lock);
        }
        else{
            pthread_mutex_unlock(td->_lock);
            break;
        }
    }
}
std::vector<Thread> Threads;

static int threadnum = 4;
int main()
{
    for (int i = 0 ;i<50 ; i++ )
    {

        std::string name = "Thread-" + std::to_string(i);
        ThreadData *td = new ThreadData(name, &gmutex);
        Thread t(name, getTicket, td);
        Threads.push_back(t);
        // Threads.emplace_back(t);
    }

    for(auto& t:Threads)
    {
        t.start();
    }

    for(auto& t:Threads)
    {
        t.join();
    }
}